package cn.fl.mfr.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.dto.SysUlDatCfgDTO;
import cmm.comm.facade.upload.dto.SysUlDatCfgDtlDTO;
import cmm.mid.core.framework.page.ListPageVO;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mfr.web.service.IMfrInfoModDtlService;
import cn.fl.mfr.web.service.IMfrInfoModService;
import cn.fl.mfr.web.vo.MfrInfoModDtlVO;
import cn.fl.mfr.web.vo.MfrInfoModVO;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSON;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import fl.spl.facade.framework.enums.SplInfoFileCfgEnum;
import fl.spl.facade.mfr.condition.MfrInfoModDtlQC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 厂商信息变更记录 控制层
 */
@Controller
@RequestMapping("/mfr/mfrinfomoddtl")
public class MfrInfoModDtlController extends BaseController {

	/**
	 * MfrInfoModDtl 服务层BEAN
	 */
	@Autowired
	private IMfrInfoModDtlService mfrInfoModDtlService;

	/**
	 * MfrInfoModDtl 服务层BEAN
	 */
	@Autowired
	private IMfrInfoModService mfrInfoModService;

	@Autowired
	private IUploadApiService uploadApiService;

	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		String modId = request.getParameter("modId");
		ModelAndView view = new ModelAndView("mfr/mfrInfoMod/mfrInfoModDtlList");
		view.addObject("modId", modId);
		if(StringUtils.isNotEmpty(modId)){
			MfrInfoModVO mfrInfoModVO = this.mfrInfoModService.selectById(Long.valueOf(modId));
			view.addObject("isFileMdf", mfrInfoModVO.getIsFileMdf());
		}
		BaseLogUtils.newWebLogger("加载列表页面").setLogOperType(LogOperEnum.REQ)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.info();
		return view;
	}
	
	/**
	 * 到新增修改页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("mfr/mfrInfoModDtl/mfrInfoModDtlAdd");
		
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mfr/mfrInfoModDtl/mfrInfoModDtlModify");
		view.addObject("id", id);
		return view;
	}
	
	/**
	 * 到详情页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("mfr/mfrInfoModDtl/mfrInfoModDtlDetail");
		view.addObject("id", id);
		
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String modId = request.getParameter("modId");

		if (StringUtils.isEmpty(modId)) {
			BaseLogUtils.newWebLogger("主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return null;
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		MfrInfoModDtlQC qc = new MfrInfoModDtlQC();
		qc.setModId(Long.valueOf(modId));
		qc.setIsDel(BaseConstant.IS_YESNO_NO);
		qc.setIsValid(BaseConstant.IS_YESNO_YES);
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.mfrInfoModDtlService.searchListPage(page);
		List<MfrInfoModDtlVO> list = (List<MfrInfoModDtlVO>) pager.getResultList();
		ListPageVO<MfrInfoModDtlVO> listPage = new ListPageVO<MfrInfoModDtlVO>(list, pager.getTotalCount());
		BaseLogUtils.newWebLogger("加载列表页面").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.setKeys("listPage", JSON.toJSONString(listPage))
				.info();
		return listPage;
	}
	
	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
		MfrInfoModDtlVO entity = null;
		try {
			entity = new MfrInfoModDtlVO();
			//TODO ADD PARAM
			Long id = this.mfrInfoModDtlService.add(entity);
			result.setData(id);
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("数据不存在!");
			return result;
		}
		MfrInfoModDtlVO entity = null;
		try {
			entity = new MfrInfoModDtlVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.mfrInfoModDtlService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("修改失败!");
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			return result;
		}
		try {
			this.mfrInfoModDtlService.removeById(Long.valueOf(id));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
		}
		
		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("主键不能为空!");
			BaseLogUtils.newWebLogger("获取数据,主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return result;
		}
		
		try {
			MfrInfoModDtlVO vo = this.mfrInfoModDtlService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("数据不存在!");
				BaseLogUtils.newWebLogger("获取数据,数据不存在").setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
						.setWarning(false)
						.warn(LogExceptionEnum.COMMON_CODE_0002);
			}
			result.setData(vo);
			BaseLogUtils.newWebLogger("获取数据").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setKeys("result", JSON.toJSONString(result))
					.info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newWebLogger("根据主键获取对象失败，业务异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("系统错误,请联系管理员!");
			BaseLogUtils.newWebLogger("根据主键获取对象失败，系统异常").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setThrowable(ex)
					.error(LogExceptionEnum.COMMON_CODE_0099);
		}
		
		return result;
	}

	/**
	 * 初始化列表
	 */
	@RequestMapping(value = "/initMfrFileInfoApplyList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initMfrFileInfoApplyList(HttpServletRequest request, HttpServletResponse response) {

		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String modId = request.getParameter("modId");

		if (StringUtils.isEmpty(modId)) {
			BaseLogUtils.newWebLogger("主键参数为空").setLogOperType(LogOperEnum.REQ)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.warn(LogExceptionEnum.COMMON_CODE_0002);
			return null;
		}
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		MfrInfoModDtlQC qc = new MfrInfoModDtlQC();
		qc.setModId(Long.valueOf(modId));
		//qc.setIsDel(BaseConstant.IS_YESNO_NO);
		qc.setModAttrFiled("files");
		page.setCondition(qc);

		//TODO SOMETHING
		Pager pager = this.mfrInfoModDtlService.searchListPage(page);
		List<MfrInfoModDtlVO> list = (List<MfrInfoModDtlVO>) pager.getResultList();
		BaseLogUtils.newWebLogger("查询成功.[变更详情]").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.setKeys("list", JSON.toJSONString(list))
				.info();

		if(CollectionUtils.isNotEmpty(list)){

			//查询资料配置，系统代码,组织架构代码,配置编号 ,业务主键
			SysUlDatCfgQueryCondition ulDatCfgQueryCondition = new SysUlDatCfgQueryCondition();
			ulDatCfgQueryCondition.setSysCd(SplSystemConstant.SPL_SYS_CD);//系统代码
			ulDatCfgQueryCondition.setOrgCd(SplSystemConstant.DEFAULT_ORG_CD);
			ulDatCfgQueryCondition.setDataId(modId);//业务主键
			ulDatCfgQueryCondition.setIsValid(BaseConstant.IS_YESNO_YES);
			List<String> cfgCdList = new ArrayList<>();
			cfgCdList.add(SplInfoFileCfgEnum.MRF023.getCode());//配置编号
			ulDatCfgQueryCondition.setCfgCdList(cfgCdList);//配置编号集合
			List<SysUlDatCfgDTO> sysUlDatCfgDTOS = this.uploadApiService.searchSysUlDatCfgList(ulDatCfgQueryCondition);
			Map<String,String> UlDatMap = new HashMap<>();
			if(CollectionUtils.isNotEmpty(sysUlDatCfgDTOS)){
				for (SysUlDatCfgDTO sysUlDatCfgDTO:sysUlDatCfgDTOS) {
					for (SysUlDatCfgDtlDTO dtlDTO : sysUlDatCfgDTO.getSysUlDatCfgDtlDTOList()) {
						UlDatMap.put(dtlDTO.getCfgDtlCd(),sysUlDatCfgDTO.getCfgNm()+dtlDTO.getDatNm());
					}
				}
			}

			List<String> ids = new ArrayList<>();
			for (MfrInfoModDtlVO mfrInfoModDtlVO:list) {
				if(StringUtils.isNotEmpty(mfrInfoModDtlVO.getModConBef())){
					if(mfrInfoModDtlVO.getModConBef().contains(",")){
						String[] str = mfrInfoModDtlVO.getModConBef().split(",");
						for (String id : str) {
							ids.add(id);
						}
					}else{
						ids.add(mfrInfoModDtlVO.getModConBef());
					}
				}
				if(StringUtils.isNotEmpty(mfrInfoModDtlVO.getModConAft())){
					if(mfrInfoModDtlVO.getModConAft().contains(",")){
						String[] str = mfrInfoModDtlVO.getModConAft().split(",");
						for (String id : str) {
							ids.add(id);
						}
					}else{
						ids.add(mfrInfoModDtlVO.getModConAft());
					}
				}
			}
			SysUlFilesRecQueryCondition qfilesQc = new SysUlFilesRecQueryCondition();
			qfilesQc.setIdList(ids);
			qfilesQc.setSysCd(SplSystemConstant.SPL_SYS_CD);
			List<SysUlFilesRecVO> sysUlFilesRecVOS = this.sysUlFilesRecService.searchList(qfilesQc);
			Map<String,SysUlFilesRecVO> fileMap = new HashMap<>();
			if(CollectionUtils.isNotEmpty(sysUlFilesRecVOS)){
				for (SysUlFilesRecVO sysUlFilesRecVO:sysUlFilesRecVOS) {
					fileMap.put(sysUlFilesRecVO.getId().toString(),sysUlFilesRecVO);
				}
			}
			BaseLogUtils.newWebLogger("查询成功.[附件信息]").setLogOperType(LogOperEnum.RESP)
					.setSysCd(CurrentThreadContext.getCurrentSysCd())
					.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
					.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
					.setWarning(false)
					.setKeys("fileMap", JSON.toJSONString(fileMap))
					.info();
			for (MfrInfoModDtlVO mfrInfoModDtlVO:list) {
				List<SysUlFilesRecVO> filesBef = new ArrayList<>();
				List<SysUlFilesRecVO> filesAft = new ArrayList<>();
				if(StringUtils.isNotEmpty(mfrInfoModDtlVO.getModConBef())){
					if(mfrInfoModDtlVO.getModConBef().contains(",")){
						String[] str = mfrInfoModDtlVO.getModConBef().split(",");
						for (String id : str) {
							filesBef.add(fileMap.get(id));
						}
					}else{
						filesBef.add(fileMap.get(mfrInfoModDtlVO.getModConBef()));
					}
				}
				if(StringUtils.isNotEmpty(mfrInfoModDtlVO.getModConAft())){
					if(mfrInfoModDtlVO.getModConAft().contains(",")){
						String[] str = mfrInfoModDtlVO.getModConAft().split(",");
						for (String id : str) {
							filesAft.add(fileMap.get(id));
						}
					}else{
						filesAft.add(fileMap.get(mfrInfoModDtlVO.getModConAft()));
					}
				}
				mfrInfoModDtlVO.setRlRem(UlDatMap.get(mfrInfoModDtlVO.getModAttrCon()));
				BaseLogUtils.newWebLogger("查询成功.[附件变更信息]:").setLogOperType(LogOperEnum.RESP)
						.setSysCd(CurrentThreadContext.getCurrentSysCd())
						.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
						.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
						.setWarning(false)
						.setKeys("filesBef", JSON.toJSONString(filesBef),"filesAft", JSON.toJSONString(filesAft))
						.info();
				mfrInfoModDtlVO.setFilesBef(filesBef);
				mfrInfoModDtlVO.setFilesAft(filesAft);
			}
		}
		ListPageVO<MfrInfoModDtlVO> listPage = new ListPageVO<MfrInfoModDtlVO>(list, pager.getTotalCount());
		BaseLogUtils.newWebLogger("加载列表页面").setLogOperType(LogOperEnum.RESP)
				.setSysCd(CurrentThreadContext.getCurrentSysCd())
				.setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
				.setBussinessId(BusinessIdConstant.LOG_PROD_MANAGER_CD)
				.setWarning(false)
				.setKeys("listPage", JSON.toJSONString(listPage))
				.info();
		return listPage;
	}

}

